﻿using CIS.DB;
using CIS.Web.Common;
using CIS.Web.Models;
using CIS.Web.Properties;
using System;
using System.Data.Entity;
using System.IO;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace CIS.Web.Controllers
{
	[RoutePrefix("MeetingApply")]
	public class MeetingApplyController : BaseDbController
	{
		public ActionResult Index()
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName);

			return View();
		}

		[HttpPost]
		[ValidateAntiForgeryToken]
		[ValidateInput(false)]
		public async Task<JsonResult> Apply(ConferenceMasterModel model, FormCollection formCollection)
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName);

			//检查会议昵称是否已存在
			var result = await DbContext.ConferenceMaster.FirstOrDefaultAsync(x => x.ConferenceNickName == model.ConferenceNickName);
			if (result != null)
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(string.Format(Resources.MsgRecordExist,
						Resources.ConferenceNickName)), JsonRequestBehavior.AllowGet);
			}

			var conferenceId = Utility.GetTableId(ConstValues.TableName.ConferenceMaster);
			var now = DateTime.Now;
			var conferenceMaster = new ConferenceMaster
			{
				ID = conferenceId,
				IsInternational = Request.Cookies["_culture"] != null && Request.Cookies["_culture"].Value == ConstValues.Language.En ? true : false,
				ConferenceModel = ConstValues.ConferenceModelStyle.Center,
				IsReview = false,
				IsDisplay = true,
				IsInHome = false,
				IsRecommend = false,
				IsDisplayMobile = false,
				IsDisplayMobileHome = false,
				RegisterStartDate = now,
				RegisterEndDate = Utility.ConvertEndDate(now),
				PayStartDate = now,
				PayEndDate = Utility.ConvertEndDate(now),
				BenefitStartDate = now,
				BenefitEndDate = Utility.ConvertEndDate(now),
				ContributeStartDate = now,
				ContributeEndDate = Utility.ConvertEndDate(now),
				ReviewStartDate = now,
				ReviewEndDate = Utility.ConvertEndDate(now),
				FinalStartDate = now,
				FinalEndDate = Utility.ConvertEndDate(now),
				HotelStartDate = now,
				HotelEndDate = Utility.ConvertEndDate(now),
				CheckinDate = now,
				CheckoutDate = Utility.ConvertEndDate(now),
				TrafficStartDate = now,
				TrafficEndDate = Utility.ConvertEndDate(now),
				OpacityOfPic = 0,
				ColorForBackground = "#ffffff",
				OpacityOfColor = 0,
				ColorForMenu = "#4c4948",
				OpacityOfMenu = 0,
				ColorForLeft = "#ffffff",
				OpacityOfLeft = 0,
				ColorForCenter = "#ffffff",
				OpacityOfCenter = 0,
				ColorForRight = "#ffffff",
				OpacityOfRight = 0,
				ColorForConference = "#c30d23",
				FontColorForMenu = "#ffffff",
				Status = ConstValues.Status.暂停,
				Sort = ConstValues.DefaultSort,
				Creator = LoginUser.UserName,
				CreateIP = LoginUser.IP,
				CreateDate = now,
			};

			string nickName = model.ConferenceNickName;
			string folder = Path.Combine(ConstValues.ConferenceImg, nickName);
			string pfolder = Path.Combine(Server.MapPath(ConstValues.ConferenceImg), nickName);

			#region 会议基本信息设置
			conferenceMaster.ConferenceName = model.ConferenceName;
			conferenceMaster.ConferenceNickName = model.ConferenceNickName;
			conferenceMaster.ConferenceStartDate = model.ConferenceStartDate;
			conferenceMaster.ConferenceEndDate = Utility.ConvertEndDate(model.ConferenceEndDate);
			conferenceMaster.OperateTime = model.OperateTime?.Trim();
			conferenceMaster.OperateLocation = model.OperateLocation?.Trim();
			conferenceMaster.ConferenceAddress = model.ConferenceAddress?.Trim();
			conferenceMaster.Sponsor = model.Sponsor?.Trim();
			conferenceMaster.CoOrganizer = model.CoOrganizer?.Trim();
			conferenceMaster.Organizer = model.Organizer?.Trim();
			conferenceMaster.HomePageUrl = model.HomePageUrl?.Trim();
			conferenceMaster.Summary = model.Summary?.Trim();
			conferenceMaster.Contact = model.Contact?.Trim();
			conferenceMaster.ContactPhone = model.ContactPhone?.Trim();
			conferenceMaster.ContactMail = model.ContactMail?.Trim();

			if (model.PicForPCFile != null)
			{
				if (model.PicForPCFile.ContentLength > ConstValues.PicMaxLength)
				{
					string errorMessage = Resources.MsgPicOverflowError;
					return JsonCamelCase(Utility.CreateFailJsonResult(errorMessage),
						JsonRequestBehavior.AllowGet);
				}

				string fileName = nickName + ConstValues.strHyphen +
						Path.GetExtension(model.PicForPCFile.FileName).Replace(".", "").ToUpper() + ConstValues.strHyphen +
						DateTime.Now.ToString("yyyy") + ConstValues.strHyphen +
						Utility.GetRandom() + Path.GetExtension(model.PicForPCFile.FileName);
				model.PicForPCFilePath = Path.Combine(folder, fileName);
				var saveFileTask = Task.Run(() =>
				{
					string pFullPath = Path.Combine(pfolder, fileName);
					if (!Directory.Exists(pfolder))
					{
						Directory.CreateDirectory(pfolder);
					}
					model.PicForPCFile.SaveAs(pFullPath);
				});
				Task.WaitAll(saveFileTask);
				conferenceMaster.PicForPC = model.PicForPCFilePath;
			}

			if (model.PicForMobileFile != null)
			{
				if (model.PicForMobileFile.ContentLength > ConstValues.PicMaxLength)
				{
					string errorMessage = Resources.MsgPicOverflowError;
					return JsonCamelCase(Utility.CreateFailJsonResult(errorMessage),
						JsonRequestBehavior.AllowGet);
				}

				string fileName = nickName + ConstValues.strHyphen +
						Path.GetExtension(model.PicForMobileFile.FileName).Replace(".", "").ToUpper() + ConstValues.strHyphen +
						DateTime.Now.ToString("yyyy") + ConstValues.strHyphen +
						Utility.GetRandom() + Path.GetExtension(model.PicForMobileFile.FileName);
				model.PicForMobileFilePath = Path.Combine(folder, fileName);
				var saveFileTask = Task.Run(() =>
				{
					string pFullPath = Path.Combine(pfolder, fileName);
					if (!Directory.Exists(pfolder))
					{
						Directory.CreateDirectory(pfolder);
					}
					model.PicForMobileFile.SaveAs(pFullPath);
				});
				Task.WaitAll(saveFileTask);
				conferenceMaster.PicForMobile = model.PicForMobileFilePath;
			}

			conferenceMaster.Keywords = model.Keywords;
			conferenceMaster.Description = model.Description;
			conferenceMaster.Remark = model.Remark?.Trim();
			#endregion

			DbContext.ConferenceMaster.Add(conferenceMaster);

			//加CA权限
			var conferenceRoleMaster = new ConferenceRoleMaster
			{
				ID = Utility.GetTableId(ConstValues.TableName.ConferenceRoleMaster),
				RoleName = ConstValues.CA,
				ConferenceId = conferenceId,
				Status = ConstValues.Status.正常,
				Sort = ConstValues.DefaultSort,
				Creator = LoginUser.UserName,
				CreateIP = LoginUser.IP,
				CreateDate = now,
			};
			DbContext.ConferenceRoleMaster.Add(conferenceRoleMaster);
			await DbContext.SaveChangesAsync();

			var role = await DbContext.ConferenceRoleMaster.AsNoTracking()
					.FirstOrDefaultAsync(x => x.ConferenceId == conferenceId && x.RoleName == ConstValues.CA);

			var user = await DbContext.SysUserMaster.AsNoTracking()
					.FirstOrDefaultAsync(x => x.UserName == LoginUser.UserName);

			var conferenceUserAndRoleRelation = new ConferenceUserAndRoleRelation
			{
				ID = Utility.GetTableId(ConstValues.TableName.ConferenceUserAndRoleRelation),
				ConferenceId = conferenceId,
				RoleId = role.ID,
				UserId = user.ID,
				Status = ConstValues.Status.正常,
				Sort = ConstValues.DefaultSort,
				Creator = LoginUser.UserName,
				CreateIP = LoginUser.IP,
				CreateDate = now,
			};
			DbContext.ConferenceUserAndRoleRelation.Add(conferenceUserAndRoleRelation);
			await DbContext.SaveChangesAsync();

			return Json(Utility.CreateSuccessJsonResult(Resources.SuccessSubmit), JsonRequestBehavior.AllowGet);
		}
	}
}